// pages/BoardGame/BoardGame.js

const app = getApp()
const db = wx.cloud.database()
const imgPrefix = "cloud://cloud1-5guctpb76a6efae2.636c-cloud1-5guctpb76a6efae2-1316724426/bg/"
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const httpUrl = "https://636c-cloud1-5guctpb76a6efae2-1316724426.tcb.qcloud.la/";

Page({

    /**
     * 页面的初始数据
     */
    data: {
      active: 0,
      dialog: [],
      defaultAvatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      question: ""
    },
    onChange(event) {
        console.log(event.detail);
        this.setData({
            active: event.detail.index
        })
        if ( event.detail.index == 2 )
            this.getComment()
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', function(data) {
            let id = data.id
            that.setData({id})
            db.collection("bgDB").doc(id).get({
                success: function(res) {
                  console.log(res.data);
                    that.setData({
                        image: res.data.pic,
                        name: res.data.name,
                        players: res.data.players,
                        difficulty: res.data.difficulty,
                        time: res.data.time,
                        point: res.data.point,
                        brief: res.data.brief,
                        rules: res.data.rules,
                        types: res.data.types,
                        comment: res.data.comment,
                        video: res.data.video
                    })
                }
            })
            
        })
        db.collection('userDB').where({
            _openid: app.globalData.openid
        }).get({
            success: (res) => {
                this.setData({
                    avatar: res.data[0].avatar
                })
            }
        })
        this.getVideo()
    },
    getVideo(){
      let that = this
      db.collection("bgDB").get({
        success:(res) =>{
          let data = res.data;
          let getVideo = []
          for(let i = 0 ; i < data.length; i++){
            let a = {
              video: data[i].video,
              name:data[i].name
            }
            getVideo.push(a)
          }
          console.log(getVideo);
          let random = Math.floor(Math.random() * 12)
          console.log(random);
          this.setData({
            getVideo,
            random
          })
        }
      })
    },  
    //tab点击事件
    handleItemTap(e){
      const {index} = e.currentTarget.dataset;
      this.setData({
        activeIndex:index
      })
    },
    commentInput(e) {
        this.setData({
            commentInput: e.detail.value
        })
    }, 
    sendComment(e) {
        let that = this
        let comment = {"openid":app.globalData.openid,"comment":this.data.commentInput,"like":{},createTime:db.serverDate()}
        console.log(this.data.id);
        wx.cloud.callFunction({
            name: 'checkContent',
            data: {
                content: this.data.commentInput
            },
            success: (res) => {
                let suggest = res.result.result.suggest // 审核建议
                let label = res.result.result.label // 退回原因
                // 100 正常；10001 广告；20001 时政；20002 色情；20003 辱骂；20006 违法犯罪；20008 欺诈；20012 低俗；20013 版权；21000 其他
                console.log(suggest)
                console.log(this.data.comment)
                let reason = {'10001': '广告','20001': '时政','20002': '色情','20003': '辱骂','20006': '犯罪','20008': '欺诈','20012': '低俗','20013': '版权','21000': '不良'}
                if (suggest != 'pass') {
                    wx.showModal({
                        title: "言论不当！",
                        content: `可能涉及${reason[label]}内容，请修改后再发吧！`,
                        showCancel: false,
                        confirmText: '知道啦',
                        confirmColor: '#f17700'
                    })
                } else {
                    db.collection('bgDB').doc(this.data.id).update({
                        data: {
                            comment: db.command.push([comment])
                        },
                        success: function(res) {
                            that.setData({
                                commentInput: ""
                            })
                            that.getComment()
                        }
                    })
                }
            }
        })
    },
    getComment() {
        let that = this
        db.collection('bgDB').doc(this.data.id).get({
            success: function(res) {
                let commentArr = res.data.comment
                console.log(commentArr);
                for ( let i in commentArr ) {
                    db.collection("userDB").where({
                        _openid: commentArr[i]['openid']
                    }).get({
                        success: function(res) {
                            if ( res.data.length == 0 ) {
                                commentArr[i]["nickname"] = "微信用户";
                                commentArr[i]["avatar"] = defaultAvatarUrl;
                            }
                            else {
                                commentArr[i]["nickname"] = res.data[0].nickname
                                commentArr[i]["avatar"] = res.data[0].avatar
                            }
                            that.setData({commentArr})
                        }
                    })
                }
            }
        })
    },  
    loadAvatar(url){
        let file = url.substr(72,url.length);
        return httpUrl + file;
    }, 
    getTip(e) {
        let num = e.currentTarget.id
        let tip = ''
        if (num == 'tip1')
            tip = this.data.name + "好玩吗"
        else if (num == 'tip2')
            tip = this.data.name + "怎么玩"
        else if (num == 'tip3')
            tip = "推荐几个与" + this.data.name + "类似的桌游"
        this.setData({question: tip})
    },
    sendQuestion(){
        let that = this
        let dialog = this.data.dialog
        let question = this.data.question
        if (question.length == 0) {
            question = this.data.name + "的规则"
        }
        dialog.push({'role':'user','content':{'question': question}})
        dialog.push({'role':'ai','content':''})
        this.setData({dialog,question: ''})
        wx.request({
            url: 'https://www.drawu.com.cn:25565/ai', //仅为示例，并非真实的接口地址
            method: 'POST',
            data: {
                question: question
            },
            success (res) {
                dialog.pop()
                console.log(res.data);
                let type = res.data.type
                if (type == "recommendation") {
                  let recommendation = res.data.recommendation
                  let bgArr = recommendation.split(',')
                  db.collection('bgDB').where({
                    name: db.command.or(bgArr)
                  }).get({
                    success: (res) => {
                      console.log(res.data);
                      let obj = {
                        type: "recommendation",
                        bgArr: res.data
                      }
                      dialog.push({'role':'ai','content': {type: "detail",detail: "您可以看看下面这三个桌游^v^"}})
                      dialog.push({'role':'ai','content': obj})
                      console.log(dialog);
                      that.setData({dialog})
                    }
                  })
                } else if (type == "video"){
                  let obj = {
                    type: "video",
                    video: res.data.video
                  }
                  dialog.push({'role':'ai','content': {type: "detail",detail: "您可以看看这个视频哦，里面有简单的教学^v^"}})
                  dialog.push({'role':'ai','content': obj})
                  that.setData({dialog})
                } else if (type == "detail") {
                  let obj = {
                    type: "detail",
                    detail: res.data.detail
                  }
                  dialog.push({'role':'ai','content': obj})
                  that.setData({dialog})
                } else {
                  let obj = {
                    type: "other",
                    answer: res.data.answer
                  }
                  dialog.push({'role':'ai','content': obj})
                  that.setData({dialog})

                }

            },
            fail: res => {
                console.log(res);
            }
          })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})